package com.qdsg.ysg.doctor.ui;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;

import androidx.annotation.RequiresApi;
import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.qdsg.ysg.doctor.R;
import com.qdsg.ysg.doctor.base.BaseActivity;
import com.qdsg.ysg.doctor.base.BaseApplication;
import com.qdsg.ysg.doctor.ui.dialog.ApplyPermissionDialog;
import com.qdsg.ysg.doctor.ui.dialog.SelectPicModeDialog;
import com.qdsg.ysg.doctor.util.ImageLoaderHelper;
import com.qdsg.ysg.doctor.util.PermissionsChecker;
import com.qdsg.ysg.doctor.util.ToastUtil;
import com.qdsg.ysg.doctor.util.UIConstants;
import com.qdsg.ysg.doctor.util.UriUtils;
import com.rest.business.RestProxy;
import com.rest.constant.JDConstant;
import com.rest.response.BaseResponse;
import com.rest.response.BaseStringResponse;
import com.rest.response.PicUploadResponse;
import com.rest.response.RegistrationDetailResponse;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by Administrator on 2020/2/10.
 */

public class AddRegistrationActivity extends BaseActivity {
    public static final int REQUEST_OPEN_CAMERA = 0x011;
    public static final int REQUEST_GALLERY = 0x022;

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;

    @BindView(R.id.edt_state)
    EditText edt_state;

    MyAdapter adapter;

    //原图像 URI
    public Uri imgUriOri;
    //原图像 路径
    public static String imgPathOri, resourceId;

    public ProgressDialog dialog;


    List<RegistrationDetailResponse.Photo> list = new ArrayList<>();
    // 所需的全部权限
    static final String[] PERMISSIONS = new String[]{
            Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE
    };
    private PermissionsChecker mPermissionsChecker; // 权限检测器
    private SelectPicModeDialog mSelectPicModeDialog = null;


    @Override
    protected void initViews() {
        recyclerView.setLayoutManager(new GridLayoutManager(this, 3));
        adapter = new MyAdapter();
        recyclerView.setAdapter(adapter);
        recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void onDraw(@NotNull Canvas c, @NotNull RecyclerView parent, @NotNull RecyclerView.State state) {
                super.onDraw(c, parent, state);
            }

            @Override
            public void getItemOffsets(@NotNull Rect outRect, @NotNull View view, @NotNull RecyclerView parent, @NotNull RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                outRect.bottom = 1;
            }
        });
        mPermissionsChecker = new PermissionsChecker(mContext);
    }

    @Override
    protected void initData() {

    }

    @Override
    protected int getLayoutResource() {
        return R.layout.aty_add_registration;
    }


    class MyAdapter extends RecyclerView.Adapter<MyAdapter.Holder> {

        public MyAdapter() {
        }

        @Override
        public MyAdapter.Holder onCreateViewHolder(ViewGroup parent, int viewType) {
            MyAdapter.Holder myHolder = new MyAdapter.Holder(LayoutInflater.from(AddRegistrationActivity.this).inflate(R.layout.item_photo, parent, false));
            return myHolder;
        }

        @Override
        public void onBindViewHolder(final MyAdapter.Holder holder, final int position) {
            if (position - list.size() == 0) {
                holder.image.setImageResource(R.mipmap.btn_add_photo);
                holder.btn_del_photo.setVisibility(View.GONE);
            } else {
                if (!TextUtils.isEmpty(list.get(position).url)) {
                    ImageLoaderHelper.getInstance().GlideImageLoaderByStream(AddRegistrationActivity.this, list.get(position).url + ".sm", holder.image);
                } else if (!TextUtils.isEmpty(list.get(position).uri)) {
                    ImageLoaderHelper.getInstance().GlideImageLoader(AddRegistrationActivity.this, list.get(position).uri, holder.image);
                }
                holder.btn_del_photo.setVisibility(View.VISIBLE);
                holder.btn_del_photo.setOnClickListener(v -> {
                    list.remove(position);
                    notifyDataSetChanged();
                });

            }
            holder.image.setOnClickListener(v -> {
                if (position - list.size() == 0) {
                    // 缺少权限时, 进入权限配置页面
                    if (mPermissionsChecker.lacksPermissions(PERMISSIONS)) {
                        checkPermission();
                    }else {
                        showSelectHeadPicDialog();
                    }

                } else if (!TextUtils.isEmpty(list.get(position).uri)) {
                    Bundle bundle = new Bundle();
                    bundle.putString("url", list.get(position).uri);
                    bundle.putInt("type", 1);
                    AddRegistrationActivity.this.startActivity(BigImageActivity.class, bundle);
                } else if (!TextUtils.isEmpty(list.get(position).url)) {
                    Bundle bundle = new Bundle();
                    bundle.putString("url", list.get(position).url);
                    bundle.putInt("type", 2);
                    AddRegistrationActivity.this.startActivity(BigImageActivity.class, bundle);
                }
            });


        }

        @Override
        public int getItemCount() {
            return list.size() + 1;
        }


        class Holder extends RecyclerView.ViewHolder {

            ImageView image;
            ImageView btn_del_photo;

            public Holder(View itemView) {
                super(itemView);
                image = itemView.findViewById(R.id.image);
                btn_del_photo = itemView.findViewById(R.id.btn_del_photo);
            }
        }
    }


//    protected void openGallery(int requestCode) {
//
//        if (ContextCompat.checkSelfPermission(this,
//                Manifest.permission.WRITE_EXTERNAL_STORAGE)
//                != PackageManager.PERMISSION_GRANTED) {
//            ActivityCompat.requestPermissions(this,
//                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
//                    10);
//
//        } else {
//            choosePhoto(requestCode);
//        }
//
//
//    }


//    private void openCamera(int requestCode) {
//        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);// 打开相机
//        File oriPhotoFile = null;
//        try {
//            oriPhotoFile = createOriImageFile();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        if (oriPhotoFile != null) {
//            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
//                imgUriOri = Uri.fromFile(oriPhotoFile);
//            } else {
//                imgUriOri = FileProvider.getUriForFile(this, "com.qdsg.ysg.doctor.provider", oriPhotoFile);
//            }
//            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
//            intent.putExtra(MediaStore.EXTRA_OUTPUT, imgUriOri);
//            startActivityForResult(intent, requestCode);
//
////            Log.i(TAG, "openCamera_imgPathOri:" + imgPathOri);
////            Log.i(TAG, "openCamera_imgUriOri:" + imgUriOri.toString());
//        }
//    }
//
//    private void choosePhoto(int requestCode) {
//        Intent intent = new Intent();
//        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
//            intent.setAction(Intent.ACTION_PICK);
////            intent.setType("image/*");//相片类型
//        } else {
//            intent.setAction(Intent.ACTION_GET_CONTENT);
////            intent.setAction(Intent.ACTION_PICK);
//        }
//        intent.setType("image/*");
//        startActivityForResult(intent, requestCode);
//    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }

        //data的返回值根据
        switch (requestCode) {
            case REQUEST_OPEN_CAMERA:
                getPresignedUrl(imgPathOri);
                break;
            case REQUEST_GALLERY:
                if (data != null) {
                    Uri imgUriSel = data.getData();
                    String imgPathSel = UriUtils.formatUri(this, imgUriSel);
//                    uploadFile( imgPathSel, photo );
                    getPresignedUrl(imgPathSel);

                }
                break;

        }
    }

    /**
     * 获取minio服务器域名
     *
     * @time 2020/12/2 10:21
     */
    private void getPresignedUrl(String imgPathSel) {

        dialog = ProgressDialog.show(AddRegistrationActivity.this, "提示", "正在上传中…", true, false, null);

        // 1-病历 2-评论(反馈) 3-头像 4-轮播图 5-用户资源 6-图标 7-封面',
        RestProxy.getInstance().getPresignedUrl("1", new Observer<BaseStringResponse>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(BaseStringResponse baseStringResponse) {
                try {
                    String data = baseStringResponse.data;
                    if (data.contains("?")) {
                        String substring = data.substring(0, data.indexOf("?"));
                        resourceId = substring.substring(substring.lastIndexOf("/") + 1);
                        Log.e("presignedUrl -----", resourceId);
                        uploadFileMinio(imgPathSel,data);
                    }

                } catch (Exception e) {
                    // 捕获异常，如果要捕获Json数据异常，写catch(JSONException e)
                    e.printStackTrace();
                    //打印出来就Log.e(TAG,Log.getStackTraceString(e));
                }

            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(AddRegistrationActivity.this, e);
            }

            @Override
            public void onComplete() {
            }
        });
    }

    /**
     * 上传图片到minio服务器
     * <p>
     * * @time 2020/12/3 15:36
     */
    private void uploadFileMinio(String imgPath,String url) {
        new Thread(() -> {
            try {
                Log.e("TAG-路径-----", imgPath);
                File file = new File(imgPath);
                FileInputStream fileInputStream = new FileInputStream(file);
                int available = fileInputStream.available(); //返回与之关联的文件的字节数
                Log.e("字节数---", available + "");

                OkHttpClient httpClient = new OkHttpClient();
                MediaType mediaType = MediaType.parse("image/png");//设置类型
                RequestBody requestBody = RequestBody.create(mediaType, file);//把文件与类型放入请求体
                Request request = new Request.Builder()
                        .url(url)
                        .put(requestBody)
                        .build(); //创建OkHttpClient对象
                Call call = httpClient.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.e("TAG-失败：", e.toString() + "");
                        dismissProgressDialog();
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String string = response.body().toString();
                        Log.e("minio成功---", string + "");
                        uploadFileTb(imgPath, available + "");
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();


    }

    /**
     * 上传照片保存到数据库
     *
     * @time 2020/12/2 9:55
     */
    private void uploadFileTb(String imgPathSel, String available) {
        // bucket:   1-病历 2-评论(反馈) 3-头像 4-轮播图 9-聊天图片 ',
        // type:   15-病历 2-评论(反馈) 30-头像 92-聊天图片 ',
        RestProxy.getInstance().uploadFileTb("1", "15", resourceId, BaseApplication.currentUserId, available, "0", new Observer<PicUploadResponse>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(PicUploadResponse picUploadResponse) {
                try {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            RegistrationDetailResponse.Photo photo = new RegistrationDetailResponse.Photo();
                            photo.uri = imgPathSel;
                            photo.resourceId = picUploadResponse.data.resourceId;
                            list.add(photo);
                            adapter.notifyDataSetChanged();
                            dialog.dismiss();
                        }
                    });

                } catch (Exception e) {
                    // 捕获异常，如果要捕获Json数据异常，写catch(JSONException e)
                    e.printStackTrace();
                    //打印出来就Log.e(TAG,Log.getStackTraceString(e));
                }

            }

            @Override
            public void onError(Throwable e) {

                ToastUtil.onError(AddRegistrationActivity.this, e);
            }

            @Override
            public void onComplete() {
//                dialog.dismiss();
            }
        });
    }


    /**
     * 创建原图像保存的文件
     *
     * @return
     * @throws IOException
     */
    protected File createOriImageFile() throws IOException {
        String imgNameOri = "HomePic_" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        File pictureDirOri = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES).getAbsolutePath() + "/OriPicture");
        if (!pictureDirOri.exists()) {
            pictureDirOri.mkdirs();
        }
        File image = File.createTempFile(
                imgNameOri,         /* prefix */
                ".jpg",             /* suffix */
                pictureDirOri       /* directory */
        );
        imgPathOri = image.getAbsolutePath();
        return image;
    }


    private void showSelectHeadPicDialog() {
        if (mSelectPicModeDialog == null) {
            // 初始化点击头像弹出的对话框
            mSelectPicModeDialog = SelectPicModeDialog.newInstance();
            mSelectPicModeDialog.setOnItemClickListener(new SelectPicModeDialog.OnItemClickListener() {
                @Override
                public void takePhotoClick() {
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    File oriPhotoFile = null;
                    try {
                        oriPhotoFile = createOriImageFile();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
                        imgUriOri = Uri.fromFile(oriPhotoFile);
                    } else {
                        imgUriOri = FileProvider.getUriForFile(AddRegistrationActivity.this, UIConstants.FILE_PROVIDER_URI, oriPhotoFile);
                    }
//                    phoneCamearUri = FileProvider.getUriForFile(PersonInfoActivity.this,"com.joyoung.robot.phone.provider",file);
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, imgUriOri);
                    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                    startActivityForResult(intent, REQUEST_OPEN_CAMERA);
                }

                @Override
                public void pickFromAlbumClick() {
                    Intent intent = new Intent(
                            Intent.ACTION_PICK,
                            MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    intent.setType("image/*");
                    startActivityForResult(intent, REQUEST_GALLERY);
                }
            });
        }
        mSelectPicModeDialog.show(getSupportFragmentManager(), "SelectPicModeDialog");
    }


    @OnClick(R.id.btn_confirm)
    void btn_confirm() {
        savePatientState();
    }


    private void savePatientState() {
        String listId = "";
        System.out.println(list.size());
        System.out.println(list.get(0).resourceId);
        for (RegistrationDetailResponse.Photo photo : list) {
            listId = listId + photo.resourceId + ",";
        }

        RestProxy.getInstance().savePatientState(BaseApplication.currentUserId, BaseApplication.currentDoctor.id, edt_state.getText().toString(), listId, new Observer<BaseResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseResponse baseResponse) {
                finish();
            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(AddRegistrationActivity.this, e);
            }

            @Override
            public void onComplete() {

            }
        });
    }

    @SuppressLint("CheckResult")
    private void checkPermission() {
        ApplyPermissionDialog applyPermissionDialog = ApplyPermissionDialog.newInstance( "3", true );
        applyPermissionDialog.show( getSupportFragmentManager(), "applyPermissionDialog" );
        applyPermissionDialog.setmListener( new ApplyPermissionDialog.OnItemClickListener() {

            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onConfirm() {
                RxPermissions permissions = new RxPermissions( AddRegistrationActivity.this );
                permissions.request( Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE )
                        .subscribe( granted -> {
                            if (granted) {
                                //已经打开权限
                                showSelectHeadPicDialog();
                            } else {
                                ToastUtil.showToast( mContext, "请同意相册和存储权限，否则功能无法使用" );
                                startNotificationSetting(mContext);
                            }
                        } );
            }

            @Override
            public void onCancel() {

            }
        } );
    }
}
